import 'package:dio/dio.dart';
import 'package:fsharing/core/models/ad.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AdStartModel extends ViewModel {
  static const String AD_URL = 'ad_url';
  final Api api;

  String _errorMessage;
  String _adUrl;

  AdStartModel(this.api) : super() {
    _initData();
  }

  String get errorMessage => _errorMessage;

  String get adUrl => _adUrl;

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      // 获取本地数据
      SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
      _adUrl = sharedPreferences.getString(AD_URL);
      if (_adUrl != null) {
        viewState = ViewState.success;
      }
      // 获取服务端数据
      List<Ad> list = await api.adStart(cancelToken);
      _adUrl = list.first?.imageUrl;
      if (_adUrl == null) {
        throw '启动页广告错误';
      }
      await sharedPreferences.setString(AD_URL, _adUrl);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
